'use strict';

import React,{Component} from 'react';
import PropTypes from 'prop-types';

import {
    AppRegistry,
    View,
    StyleSheet,
    ListView,
    FlatList,
} from 'react-native';

class CollectionView extends Component{

    static propTypes = {
        groupStyle:View.propTypes.style,
        items:PropTypes.array,
        itemsPerRow:PropTypes.number,
        renderItem:PropTypes.func,
    }

    static defaultProps = {
        itemsPerRow:2,
        renderItem:[],
    }

    constructor(props){
        super(props)
        this.state={}
    }
    groupItems(items, itemsPerRow) {
        let itemsGroups = [];
        let group = [];
        items.forEach(function(item) {
            if (group.length === itemsPerRow) {
                itemsGroups.push(group);
                group = [item];
            } else {
                group.push(item);
            }
        });

        if (group.length > 0) {
            itemsGroups.push(group);
        }

        return itemsGroups;
    }
    renderGroup=(group,rowIndex)=>{
        const {groupStyle} = this.props
        const that = this;
        const items = group.map(function(item, index) {
            return that.props.renderItem(item, index);
        });
        return (
            <View key={`grid-view-item-${rowIndex}`} style={[styles.group,groupStyle]}>
                {items}
            </View>
        );
    }

    render() {
        const groups = this.groupItems(this.props.items, this.props.itemsPerRow);
        const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        return (<ListView
            {...this.props}
            renderRow={this.renderGroup}
            dataSource={ds.cloneWithRows(groups)}
        />);
    }
}


const styles = StyleSheet.create({
    group: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        overflow: 'hidden'
    }
});

export default CollectionView;